package de.ohmhochschule.bme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class WebServiceActivity extends Activity {

	private EditText editText;
	private TextView textView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		editText = (EditText) findViewById(R.id.editText1);
		textView = (TextView) findViewById(R.id.textView1);
		textView.setText("");

		Button button = (Button) findViewById(R.id.btn_Translate);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i(getLocalClassName(),"hi");
				String facebookUser = editText.getText().toString();
				JSONObject jsonObject = lookupOnFacebook(facebookUser);

				if (jsonObject != null) {
					String text = "Could not find " + facebookUser;
					try {
						text = "id: " + jsonObject.getString("id");
						text += "\nname: " + jsonObject.getString("name");
						text += "\nlikes: " + jsonObject.getInt("likes");
						text += "\nlocation: "
								+ jsonObject.getJSONObject("location")
										.getString("city");
					} catch (JSONException e) {
						e.printStackTrace();
					} finally {
						textView.setText(text);
					}
				} else {
					textView.setText("Could not find " + facebookUser);
				}

			}

			private JSONObject lookupOnFacebook(String facebookUser) {
				JSONObject jsonObject = null;
				HttpURLConnection connection = null;

				try {
					URL url = new URL("http://graph.facebook.com/"
							+ facebookUser);
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setReadTimeout(5000);
					connection.setConnectTimeout(10000);
					connection.setDoInput(true);
					connection.connect();

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(connection.getInputStream(),
									"UTF-8"));
					String content = reader.readLine();
					reader.close();

					jsonObject = new JSONObject(content);

				} catch (Exception e) {
					Log.e(getLocalClassName(), e.toString());
				} finally {
					if (connection != null) {
						connection.disconnect();
						connection = null;
					}
				}
				return jsonObject;
			}
		});
	}

}